<?php

/**
 * 73YC 用户帐号相关函数库
 * ============================================================================
 * * 版权所有 2013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/**
 * 用户注册，登录函数
 *
 * @access  public
 * @param   string       $username          注册用户名
 * @param   string       $password          用户密码
 * @param   string       $email             注册email
 * @param   array        $other             注册的其他信息
 *
 * @return  bool         $bool
 */
function register($username, $password, $email, $mobile_phone)
{
    /* 检查注册是否关闭 */
    if (!empty($GLOBALS['_CFG']['shop_reg_closed']))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['shop_register_closed']);
    }
    /* 检查username */
    if (empty($username))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['username_empty']);
    }
    else
    {
        if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username))
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_invalid'], htmlspecialchars($username)));
        }
    }

    /* 检查email */
    // if (empty($email))
    // {
    //     $GLOBALS['err']->add($GLOBALS['_LANG']['email_empty']);
    // }
    // else
    // {
    //     if (!is_email($email))
    //     {
    //         $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], htmlspecialchars($email)));
    //     }
    // }

    if ($GLOBALS['err']->error_no > 0)
    {
        return false;
    }

    /* 检查是否和管理员重名 */
    if (admin_registered($username))
    {
        $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_exist'], $username));
        return false;
    }


    if (!$GLOBALS['user']->add_user($username, $password, $email ,$mobile_phone))
    {
        if ($GLOBALS['user']->error == ERR_INVALID_USERNAME)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_invalid'], $username));
        }
        elseif ($GLOBALS['user']->error == ERR_USERNAME_NOT_ALLOW)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_not_allow'], $username));
        }
        elseif ($GLOBALS['user']->error == ERR_USERNAME_EXISTS)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_exist'], $username));
        }
        elseif ($GLOBALS['user']->error == ERR_INVALID_EMAIL)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], $email));
        }
        elseif ($GLOBALS['user']->error == ERR_EMAIL_NOT_ALLOW)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_not_allow'], $email));
        }
        elseif ($GLOBALS['user']->error == ERR_EMAIL_EXISTS)
        {
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_exist'], $email));
        }
        else
        {
            $GLOBALS['err']->add('UNKNOWN ERROR!');
        }
    

        //注册失败
        return false;
    }
    else
    {
        //注册成功

        /* 设置成登录状态 */
        $GLOBALS['user']->set_session($username);
        $GLOBALS['user']->set_cookie($username);

        /* 注册送积分 */
        if (!empty($GLOBALS['_CFG']['register_points']))
        {
            log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], $GLOBALS['_LANG']['register_points']);
        }

        // 如果注册已经进行手机验证时，设置已验证！
        if($mobile_phone){
            $sql = 'UPDATE '. $GLOBALS['ecs']->table('users') . ' SET is_mobile_validated = 1 WHERE user_id = ' . $_SESSION['user_id'];

            $GLOBALS['db']->query($sql);
        }
        update_user_info();      // 更新用户信息

        return true;
    }
}

/**
 *
 *
 * @access  public
 * @param
 *
 * @return void
 */
function logout()
{
/* todo */
}

/**
 *  将指定user_id的密码修改为new_password。可以通过旧密码和验证字串验证修改。
 *
 * @access  public
 * @param   int     $user_id        用户ID
 * @param   string  $new_password   用户新密码
 * @param   string  $old_password   用户旧密码
 * @param   string  $code           验证码（md5($user_id . md5($password))）
 *
 * @return  boolen  $bool
 */
function edit_password($user_id, $old_password, $new_password='', $code ='')
{
    if (empty($user_id)) $GLOBALS['err']->add($GLOBALS['_LANG']['not_login']);

    if ($GLOBALS['user']->edit_password($user_id, $old_password, $new_password, $code))
    {
        return true;
    }
    else
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['edit_password_failure']);

        return false;
    }
}

/**
 *  会员找回密码时，对输入的用户名和邮件地址匹配
 *
 * @access  public
 * @param   string  $user_name    用户帐号
 * @param   string  $email        用户Email
 *
 * @return  boolen
 */
function check_userinfo($user_name, $email)
{
    if (empty($user_name) || empty($email))
    {
        ecs_header("Location: user.php?act=get_password\n");

        exit;
    }

    /* 检测用户名和邮件地址是否匹配 */
    $user_info = $GLOBALS['user']->check_pwd_info($user_name, $email);
    if (!empty($user_info))
    {
        return $user_info;
    }
    else
    {
        return false;
    }
}

/**
 *  用户进行密码找回操作时，发送一封确认邮件
 *
 * @access  public
 * @param   string  $uid          用户ID
 * @param   string  $user_name    用户帐号
 * @param   string  $email        用户Email
 * @param   string  $code         key
 *
 * @return  boolen  $result;
 */
function send_pwd_email($uid, $user_name, $email, $code)
{
    if (empty($uid) || empty($user_name) || empty($email) || empty($code))
    {
        ecs_header("Location: user.php?act=get_password\n");

        exit;
    }

    /* 设置重置邮件模板所需要的内容信息 */
    $template    = get_mail_template('send_password');
    $reset_email = $GLOBALS['ecs']->url() . 'user.php?act=get_password&uid=' . $uid . '&code=' . $code;
    $GLOBALS['smarty']->assign('user_name',   $user_name);
    $GLOBALS['smarty']->assign('reset_email', $reset_email);
    $GLOBALS['smarty']->assign('shop_name',   $GLOBALS['_CFG']['shop_name']);
    $GLOBALS['smarty']->assign('send_date',   date('Y-m-d'));
    $GLOBALS['smarty']->assign('sent_date',   date('Y-m-d'));
    $content = $GLOBALS['smarty']->fetch('str:' . $template['template_content']);
    /* 发送确认重置密码的确认邮件 */
    if (send_mail($user_name, $email, $template['template_subject'], $content, $template['is_html']))
    {
        return true;
    }
    else
    {
        return false;
    }
}
/**
 *  用户进行密码找回操作时，发送一封验证邮件
 *
 * @access  public
 * @param   string  $user_info    用户信息
 * @param   string  $email        用户Email
 *
 * @return  boolen  $result;
 */
function send_retrieve_hash($user_name,$email,$user_info)
{
    /* 设置验证邮件模板所需要的内容信息 */
    $template    = get_mail_template('send_password');
    $hash = register_hash('encode', $user_info);
    $reset_email = $GLOBALS['ecs']->url() . 'user.php?act=get_password&hash=' . $hash;
    $GLOBALS['smarty']->assign('user_name',   $user_name);
    $GLOBALS['smarty']->assign('reset_email',    $reset_email);
    $content = $GLOBALS['smarty']->fetch('str:' . $template['template_content']);
    /* 发送激活重置密码邮件 */
    if (send_mail('', $email, $template['template_subject'], $content, $template['is_html']))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 *  发送注册邮件
 *
 * @access  public
 * @param   int     $user_info        用户数据
 * @param   int     $email            发送地址
 * @return boolen
 */
function send_regiter_hash ($email,$user_info)
{   

    /* 设置验证邮件模板所需要的内容信息 */
    $template    = get_mail_template('register_validate');

    $hash = register_hash('encode', $user_info);
    $validate_email = $GLOBALS['ecs']->url() . 'user.php?act=validate_email&hash=' . $hash;
    $GLOBALS['smarty']->assign('validate_email',    $validate_email);
    $content = $GLOBALS['smarty']->fetch('str:' . $template['template_content']);
    /* 发送激活验证邮件 */
    if (send_mail('', $email, $template['template_subject'], $content, $template['is_html']))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 *  生成邮件验证hash
 *
 * @access  public
 * @param   $operation 操作方式加密或解密
 * @param   $data 数据
 * @return void
 */
function register_hash ($operation, $data)
{
    if ($operation == 'encode')
    {

        // $sql = "SELECT reg_time ".
        //        " FROM " . $GLOBALS['ecs'] ->table('users').
        //        " WHERE user_id = '$user_id' LIMIT 1";
        // $reg_time = $GLOBALS['db']->getOne($sql);
        /*判断数据是否为数组转换为JSON对象*/
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $reg_time = 123;
        $hash = substr(md5($data . $GLOBALS['_CFG']['hash_code'] . $reg_time), 16, 4);

        return base64_encode($data . '--' . $hash);
    }
    else
    {
        $hash = base64_decode(trim($data));
        $row = explode('--', $hash);
        if (count($row) != 2)
        {
            return 0;
        }
        $data = $row[0];

        $salt = trim($row[1]);

        if (empty($data) || strlen($salt) != 4)
        {
            return 0;
        }

        // $sql = "SELECT reg_time ".
        //        " FROM " . $GLOBALS['ecs'] ->table('users').
        //        " WHERE user_id = '$user_id' LIMIT 1";
        // $reg_time = $GLOBALS['db']->getOne($sql);
        $reg_time = 123;
        $pre_salt = substr(md5($data . $GLOBALS['_CFG']['hash_code'] . $reg_time), 16, 4);

        if ($pre_salt == $salt)
        {
            $data=json_decode($data);
            return $data;
        }
        else
        {
            return 0;
        }
    }
}

/**
 * 判断超级管理员用户名是否存在
 * @param   string      $adminname 超级管理员用户名
 * @return  boolean
 */
function admin_registered( $adminname )
{
    $res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('admin_user') .
                                  " WHERE user_name = '$adminname'");
    return $res;
}

?>